package com.richard.cloud.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.richard.cloud.entity.Order;
import com.richard.cloud.feign.SeataAccountServiceFeign;
import com.richard.cloud.feign.SeataStorageServiceFeign;
import com.richard.cloud.repo.OrderRepo;

import cn.hutool.core.lang.UUID;
import io.seata.spring.annotation.GlobalTransactional;

@Service
public class OrderService {
	@Resource
	private OrderRepo repo;
	@Resource
	private SeataAccountServiceFeign accountService;
	@Resource
	private SeataStorageServiceFeign storageService;
	
	/**
	 * 创建订单
	 * @param order
	 */
	@GlobalTransactional
	public Order createOrder(Order order) {
		//本地新增订单，状态-新建
		order.setOrderNo(UUID.fastUUID().toString());
		order.setStatus("create");
		Order save = repo.save(order);
		
		//调用库存微服务，扣减商品库存
		storageService.decrease(save.getProdId(), save.getCount());
		
		//调用账户微服务，账户扣钱
		accountService.charge(save.getCustId(), save.getAmount());
		
		//本地修改订单，状态-完成
		save.setStatus("finish");
		return repo.saveAndFlush(save);
	}
}
